﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Objects.SqlClient;

using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;

namespace BookStore
{
    public partial class SachPage : System.Web.UI.Page
    {
        static BookStoreEntities entities = new BookStoreEntities();
        protected void Page_Load(object sender, EventArgs e)
        {

            /*if (this.IsPostBack) return;
            {
                this.ProductsGrid.DataBind();
            }*/
            //These lines used to enable or disable "All" Link for LoaiSach 
            string LoaiSach = Request.QueryString["loaisach"];
            string NhaXuatBan = Request.QueryString["nxb"];
            string SachBanChay = Request.QueryString["sachbanchay"];
            string SachMoi = Request.QueryString["sachmoi"];
            string key = Request.QueryString["key"];

            leftPanel_AllBookLabel.Visible = false;
            leftPanel_BestSellerLabel.Visible = false;
            leftPanel_NewBookLabel.Visible = false;

            //If no querystring variables were set, show all books
            if (LoaiSach == null && NhaXuatBan == null && SachBanChay == null && SachMoi == null && key == null)
            {
                PageTitle.Text = "Tất cả";
                leftPanel_AllBookLink.Visible = false;
                leftPanel_AllBookLabel.Visible = true;
                ProductsGrid.DataSourceID = "TatCaSachDS";
                ProductsGrid.DataBind();
            }
            else
            {
                if (key != null)
                {
                    ProductsGrid.DataSourceID = "TimKiemDS";
                    PageTitle.Text = "Kết quả tìm kiếm cho: \"" + key + "\"";
                }

                //Set PageTitle = Bán Chạy Nhất if QueryString["sachbanchay"] = "1"
                if (SachBanChay != null)
                {
                    if (SachBanChay == "1")
                    {
                        ProductsGrid.DataSourceID = "SachBanChayDS";
                        PageTitle.Text = "Bán chạy nhất";
                        leftPanel_BestSellerLabel.Visible = true;
                        leftPanel_BestSellerLink.Visible = false;
                    }
                    else //If not, show nothing
                    {
                        PageTitle.Text = "Not Found";
                    }
                }

                //Set PageTitle = Sách mới if QueryString["sachmoi"] = "1"
                if (SachMoi != null)
                {
                    if (SachMoi == "1")
                    {
                        ProductsGrid.DataSourceID = "SachMoiDS";
                        PageTitle.Text = "Sách mới";
                        leftPanel_NewBookLabel.Visible = true;
                        leftPanel_NewBookLink.Visible = false;
                    }
                    else //If not, show nothing
                    {
                        PageTitle.Text = "Not Found";
                    }
                }
                if (NhaXuatBan != null || LoaiSach != null)
                {
                    ProductsGrid.DataSourceID = "DSachSachDS";
                    if (NhaXuatBan != null && LoaiSach == null)
                    {
                        leftPanel_AllBookLabel.Visible = false;
                        int MaNXB = Convert.ToInt32(NhaXuatBan);
                        var nxb = (from n in entities.NhaXuatBans
                                   where n.MaNXB == MaNXB
                                   select n).SingleOrDefault();
                        if (nxb != null)
                        {
                            PageTitle.Text = nxb.TenNXB;
                        }
                        else //If no records were found, Page Title = Not Found
                        {
                            PageTitle.Text = "Not Found";
                        }
                    }
                    else if (NhaXuatBan == null && LoaiSach != null) //Show Books from a specific LoaiSach
                    {
                        leftPanel_AllBookLabel.Visible = false;
                        int MaLoaiSach = Convert.ToInt32(LoaiSach);
                        var loaisach = (from n in entities.LoaiSaches
                                        where n.MaLoaiSach == MaLoaiSach
                                        select n).SingleOrDefault();
                        if (loaisach != null)
                        {
                            PageTitle.Text = loaisach.TenLoaiSach;
                        }
                        else //If no records were found, Page Title = Not Found
                        {
                            PageTitle.Text = "Not Found";
                        }
                    }
                    else
                    {
                        PageTitle.Text = "URL Not Found";
                    }
                }
            }
            SetPostBackLink(LoaiSach, NhaXuatBan);
        }

        protected int GetCurrentPageIndex()
        {
            string page = Request.QueryString["page"];
            int currentPage = 1;
            if (page != null)
            {
                currentPage = Convert.ToInt32(page);
            }
            return currentPage;
        }

        protected void SetPostBackLink(string LoaiSach, string NhaXuatBan)
        {
            int currentPage = GetCurrentPageIndex();
            int pageSize = 8;
            int recordCount = 0;

            string DSName = ProductsGrid.DataSourceID;
            switch (DSName)
            {
                case "TatCaSachDS":
                    recordCount = (from s in entities.Saches
                                   select s).Count();
                    break;
                case "DSachSachDS":
                    int MaLoaiSach = Convert.ToInt32(LoaiSach);
                    int MaNXB = Convert.ToInt32(NhaXuatBan);
                    recordCount = (from s in entities.Saches
                                   where s.MaLoaiSach == MaLoaiSach
                                    || s.MaNXB == MaNXB
                                   select s).Count();
                    break;
                case "SachMoiDS":
                    DateTime now = DateTime.Now;
                    recordCount = (from s in entities.Saches
                                   where SqlFunctions.DateDiff("d", s.NgayXuatBan, now) < 45
                                   select s).Count();
                    break;
                case "SachBanChayDS":
                    System.Data.Objects.ObjectParameter count = new System.Data.Objects.ObjectParameter("count", typeof(int));
                    entities.CountBestSeller(count);
                    recordCount = (int)count.Value;
                    break;
                default:
                    recordCount = 0;
                    break;
            }

            int maxPageIndex = recordCount / pageSize;
            if (recordCount % pageSize > 0)
            {
                maxPageIndex += 1;
            }
            if (maxPageIndex == 0)
                currentPage = 0;

            string nextPageUrl = (Request.QueryString["page"] == null) ? "?page=2&" : "?"; ;
            string prevPageUrl = "?";

            //Set PostBackUrl for PrevPage LinkButton
            if (currentPage > 1 && currentPage <= maxPageIndex)
            {
                PrevPage.Enabled = true;
                foreach (string key in Request.QueryString.AllKeys)
                {
                    if (key != "page")
                    {
                        prevPageUrl += key + "=" + Request.QueryString[key];
                    }
                    else
                    {
                        prevPageUrl += "page=" + (currentPage - 1).ToString();
                    }
                    prevPageUrl += "&";
                }
                PrevPage.PostBackUrl = prevPageUrl.Remove(prevPageUrl.Length - 1);
            }
            else
            {
                PrevPage.Enabled = false;
            }

            //Set PostBackUrl for NextPage LinkButton
            if (currentPage >= 1 && currentPage < maxPageIndex)
            {
                NextPage.Enabled = true;
                foreach (string key in Request.QueryString.AllKeys)
                {
                    if (key != "page")
                    {
                        nextPageUrl += key + "=" + Request.QueryString[key];
                    }
                    else
                    {
                        nextPageUrl += "page=" + (currentPage + 1).ToString();
                    }
                    nextPageUrl += "&";
                }
                NextPage.PostBackUrl = nextPageUrl.Remove(nextPageUrl.Length - 1);
            }
            else
            {
                NextPage.Enabled = false;
            }
            CurrentPage.Text = "Trang: " + currentPage.ToString() + "/" + maxPageIndex.ToString();
        }

        protected void ProductsGrid_ItemCommand(object source, DataListCommandEventArgs e)
        {
            //
            if (e.CommandName == "datmua")
            {
                //lay id tu commandagrument
                Basket gio = (Basket)Session["GioHang"];
                Label lblten = (Label)e.Item.FindControl("lbl_ten");
                Image imgProduct = (Image)e.Item.FindControl("img_product");
                HiddenField txtCCao = (HiddenField)e.Item.FindControl("txtCCao");
                HiddenField txtCRong = (HiddenField)e.Item.FindControl("txtCRong");
                HiddenField txtBDay = (HiddenField)e.Item.FindControl("txtBDay");
                HiddenField txtKLuong = (HiddenField)e.Item.FindControl("txtKLuong");

                string id = e.CommandArgument.ToString();
                HiddenField lblgia = (HiddenField)e.Item.FindControl("lbl_gia");
                int soluong = 1;
                if (gio != null)
                {
                    gio.Add(id, lblten.Text, DateTime.Now, "", imgProduct.ImageUrl, Convert.ToInt32(txtCCao.Value),
                        Convert.ToInt32(txtCRong.Value),
                        Convert.ToInt32(txtBDay.Value),
                        Convert.ToInt32(txtKLuong.Value), soluong, Convert.ToInt32(lblgia.Value));
                }
                else
                {
                    Session["GioHang"] = new Basket();
                }
                Response.Write("<div class='added-item-alert'>" + lblten.Text + " have added to your ShoppingCart</div>");
            }
        }
    }
}